/* NOTICE
 
    Jim - the Java Image Manager, copyright (c) 2005 - 2007 Grant Gardner 
 
    Jim is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    Jim is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program.  If not, see <http://www.gnu.org/licenses/>.
  
    In addition, as a special exception, you are permitted to link this code
    with the 3rd party libraries required to compile this file and to
    distribute a linked combination including them. You must obey the
    GNU General Public License in all respects for all of the code except for
    those 3rd party libraries that are licenced under terms incompatible with the
    GNU General Public License.  
 
 
 NOTICE */

/*
 * Created on 13/10/2004
 *
 */

package au.com.lastweekend.jim.imagebase;

import java.io.File;
import java.util.Collection;
import java.util.HashSet;
import java.util.Hashtable;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;

import javax.naming.NameNotFoundException;
import javax.naming.NamingEnumeration;
import javax.naming.NamingException;
import javax.naming.directory.Attribute;
import javax.naming.directory.Attributes;
import javax.naming.directory.BasicAttribute;
import javax.naming.directory.BasicAttributes;
import javax.naming.directory.DirContext;
import javax.naming.directory.InitialDirContext;
import javax.naming.directory.ModificationItem;
import javax.naming.directory.SearchControls;
import javax.naming.directory.SearchResult;

import org.apache.log4j.Logger;

import au.com.lastweekend.jim.imagebase.query.CombinationCondition;
import au.com.lastweekend.jim.imagebase.query.LDAPCombinationCondition;
import au.com.lastweekend.jim.imagebase.query.LDAPCondition;
import au.com.lastweekend.jim.imagebase.query.LDAPEqualsCondition;
import au.com.lastweekend.jim.imagebase.query.QueryCondition;
import au.com.lastweekend.jim.io.metadata.Tag;
import au.com.lastweekend.jim.util.StringUtils;

/**
 * @author grant@lastweekend.com.au
 * @version $Id: LDAPImageBase.java,v 1.10 2006/03/01 09:52:04 ggardner Exp $
 */
public class LDAPImageBase extends 
AbstractImageBase implements ImageBase {

    private static final Logger LOG = Logger.getLogger(LDAPImageBase.class);
    private final Hashtable<String, String> env = new Hashtable<String, String>();
    private String ldapUrlString;

    private SoftHashMap<String, ImageBaseDirectory> imageBaseDirectoryMap = new SoftHashMap<String, ImageBaseDirectory>();
    private Set<String> storedKeywords;
    private TagHandlerFactory tagHandlerFactory;

    /**
     * Creates an imageBase with given LDAP connection parameters and URL
     * 
     * <code>
     *  env = new HashMap();
     *  env.put(Context.SECURITY_AUTHENTICATION, "simple");
     *  env.put(Context.SECURITY_PRINCIPAL, "cn=Manager, dc=my-domain,dc=com");
     *  env.put(Context.SECURITY_CREDENTIALS, "secret");
     * 
     *  new ImageBase(env,"ldap://localhost:389/dc=my-domain,dc=com");
     * </code>
     * 
     * @param ldapEnv
     * @param ldapUrlString
     * @param factory
     */
    public LDAPImageBase(Map<String, String> ldapEnv, String ldapUrlString, TagHandlerFactory factory) {

        env.putAll(ldapEnv);
        this.ldapUrlString = ldapUrlString;
        this.tagHandlerFactory = factory;
        DirContext dirContext = getDirectoryContext();
        LOG.info("Connected to " + ldapUrlString);
        cleanup(dirContext);
    }

    /**
     * @return
     */
    private DirContext getDirectoryContext() {

        try {
            return (DirContext) new InitialDirContext(env).lookup(ldapUrlString);
        } catch (NamingException e) {
            throw new ImageBaseRuntimeException("Can't connect to ldap", e);
        }
    }

    /**
     * @param filename
     * 
     * @return the imagebasedirectory at filename
     */
    public ImageBaseDirectory findDirectory(String filename) {

        ImageBaseDirectory imageBaseDirectory = imageBaseDirectoryMap.get(filename);
        if (imageBaseDirectory == null) {
            DirContext dirContext = getDirectoryContext();

            try {
                Attributes attrs = dirContext.getAttributes("cn=" + filename);
                imageBaseDirectory = new ImageBaseDirectory();
                loadDirectory(imageBaseDirectory, attrs);

            } catch (NameNotFoundException nnfe) {
                if (LOG.isDebugEnabled()) {
                    LOG.debug("No directory for " + filename, nnfe);
                }
                return null;
            } catch (NamingException e) {
                throw new ImageBaseRuntimeException("Unexpected exception searching for " + filename, e);
            } finally {
                cleanup(dirContext);
            }
        }

        return imageBaseDirectory;
    }

    /**
     * @param imageBaseDirectory
     * @param attrs
     * @throws NamingException
     */
    private void loadDirectory(ImageBaseDirectory imageBaseDirectory, Attributes attrs) throws NamingException {

        imageBaseDirectory.setTag(ImageBaseDirectory.TAG_TITLE, 0, "");
        NamingEnumeration<? extends Attribute> namingEnum = attrs.getAll();
        String fileName = null;
        while (namingEnum.hasMoreElements()) {
            Attribute attribute = namingEnum.nextElement();
            if (attribute.getID().equals("cn")) {
                fileName = (String) attribute.get();
                imageBaseDirectory.setTag(ImageBaseDirectory.TAG_FILENAME, 0, fileName);

            }

            if (attribute.getID().equals("title")) {
                imageBaseDirectory.setTitle((String) attribute.get());
            }
            if (attribute.getID().equals("path")) {
                NamingEnumeration<?> pathsEnum = attribute.getAll();
                Set<File> paths = new HashSet<File>();

                while (pathsEnum.hasMoreElements()) {
                    File filePath = new File((String) pathsEnum.nextElement());
                    paths.add(ImageBaseDirectory.convertToImageBaseFile(filePath));
                }
                imageBaseDirectory.setPaths(paths);
            }
            if (attribute.getID().equals("keywords")) {
                NamingEnumeration<?> keywordsEnum = attribute.getAll();
                Set<String> keywords = new HashSet<String>();

                while (keywordsEnum.hasMoreElements()) {
                    keywords.add((String) keywordsEnum.nextElement());
                }

                imageBaseDirectory.setKeywords(keywords);
            }

        }
        if (fileName == null) {
            throw new IllegalStateException("No filename found " + attrs);
        }

        imageBaseDirectoryMap.put(fileName, imageBaseDirectory);
        imageBaseDirectory.setTagHandler(tagHandlerFactory.makeTagHandler(this, imageBaseDirectory));
    }

    private void cleanup(DirContext dirContext) {

        try {
            dirContext.close();
        } catch (NamingException e1) {
            LOG.warn(e1);
        }
    }

    public void storeDirectory(ImageBaseDirectory imageBaseDirectory) {

        DirContext dirContext = getDirectoryContext();
        String fileName = imageBaseDirectory.getFilename();
        try {
            String name = "cn=" + fileName;
            BasicAttributes attrs = new BasicAttributes();
            Attribute objectClass = new BasicAttribute("objectclass");
            objectClass.add("jimPhoto");
            objectClass.add("extensibleObject");
            attrs.put(objectClass);

            Iterator<Tag> tagIter = imageBaseDirectory.getTagIterator();
            while (tagIter.hasNext()) {
                Tag tag = tagIter.next();
                addTagToAttributes(tag.getTagType(), tag.getFormatCode(), imageBaseDirectory.getObject(tag.getTagType()), attrs);

            }

            dirContext.bind(name, null, attrs);
            imageBaseDirectoryMap.put(fileName, imageBaseDirectory);
            imageBaseDirectory.setTagHandler(tagHandlerFactory.makeTagHandler(this, imageBaseDirectory));

        } catch (NamingException e) {
            throw new ImageBaseRuntimeException("Unexpected error binding directory for " + fileName, e);
        } finally {
            cleanup(dirContext);
        }

    }

    public void removeDirectory(ImageBaseDirectory imageDirectory) {

        DirContext dirContext = getDirectoryContext();
        String fileName = imageDirectory.getFilename();
        String name = "cn=" + fileName;

        try {
            dirContext.unbind(name);
            imageBaseDirectoryMap.remove(fileName);
        } catch (NamingException e) {
            LOG.error("Error unbinding directory for " + fileName, e);
        } finally {
            cleanup(dirContext);
        }

    }

    /**
     * @param imageDirectory
     * @param tagType
     * @param formatCode
     * @param value
     */
    public void replaceTag(ImageBaseDirectory imageDirectory, int tagType, int formatCode, Object value) {

        DirContext dirContext = getDirectoryContext();
        try {
            Attributes attributes = new BasicAttributes();

            addTagToAttributes(tagType, formatCode, value, attributes);
            dirContext.modifyAttributes(getRDN(imageDirectory), DirContext.REPLACE_ATTRIBUTE, attributes);
        } catch (NamingException e) {
            LOG.error("Error replacing tag " + tagType + " with value " + value, e);
        } finally {
            cleanup(dirContext);
        }

    }

    @SuppressWarnings("unchecked")
    private void addTagToAttributes(int tagType, int formatCode, Object value, Attributes attributes) {

        String attributeName = getAttributeName(tagType);
        switch (formatCode) {
            case ImageBaseDirectory.FMT_STRING :
                if (!StringUtils.isBlank((String) value)) {
                    attributes.put(attributeName, value);
                }

                break;
            case ImageBaseDirectory.FMT_FILE_SET :
            case ImageBaseDirectory.FMT_STRING_SET :
                BasicAttribute multiValuedAttribute = new BasicAttribute(attributeName);
                Iterator valueIter = ((Set) value).iterator();
                while (valueIter.hasNext()) {
                    String valueItem = valueIter.next().toString();
                    multiValuedAttribute.add(valueItem);
                }
                if (multiValuedAttribute.size() > 0) {
                    attributes.put(multiValuedAttribute);
                }
                break;
            default :
                LOG.warn("Unknown format code: " + formatCode + " for attribute: " + attributeName + " for tag: " + tagType);
                break;
        }
    }

    /**
     * @param imageDirectory
     * @return
     */
    private String getRDN(ImageBaseDirectory imageDirectory) {

        return "cn=" + imageDirectory.getFilename();
    }

    /**
     * @param tagType
     * @return
     */
    private String getAttributeName(int tagType) {

        switch (tagType) {
            case ImageBaseDirectory.TAG_FILENAME :
                return "cn";

            case ImageBaseDirectory.TAG_TITLE :
                return "title";
            case ImageBaseDirectory.TAG_PATHS :
                return "path";
            case ImageBaseDirectory.TAG_KEYWORDS :
                return "keywords";
            default :
                throw new ImageBaseRuntimeException("Unknown tag " + tagType);

        }
    }

    /**
     * @param searchString
     * @return collection of ImageBaseDirectory-s that match the search
     */
    public Set<ImageBaseDirectory> search(String searchString) {

        DirContext dirContext = getDirectoryContext();
        Set<ImageBaseDirectory> results = new HashSet<ImageBaseDirectory>();
        try {
            NamingEnumeration<SearchResult> names = dirContext.search("", searchString, new SearchControls());
            while (names.hasMoreElements()) {

                SearchResult searchResult = names.nextElement();
                ImageBaseDirectory imageDirectory = new ImageBaseDirectory();
                loadDirectory(imageDirectory, searchResult.getAttributes());
                if (!imageDirectory.getFilename().equals("jimConfig")) {
                    results.add(imageDirectory);
                }

            }
        } catch (NamingException e) {
            throw new ImageBaseRuntimeException("Naming exception searching for " + searchString, e);
        } finally {
            cleanup(dirContext);
        }

        return results;
    }

    public Set<String> getStoredKeywords() {

        if (storedKeywords == null) {
            storedKeywords = new HashSet<String>();
            DirContext dirContext = getDirectoryContext();
            try {
                Attributes attrs = dirContext.getAttributes("cn=jimConfig");
                Attribute keywordAttr = attrs.get("keywords");
                if (keywordAttr != null) {
                    for (int i = 0; i < keywordAttr.size(); i++) {
                        storedKeywords.add((String) keywordAttr.get(i));
                    }
                }
            } catch (NamingException e) {
                LOG.warn("Naming exception loading keywords", e);
            } finally {
                cleanup(dirContext);
            }
        }
        LOG.debug(storedKeywords);
        return storedKeywords;
    }

    /**
     * @param newKeywordString
     */
    public void addKeyword(String newKeywordString) {

        LOG.debug("Adding Keyword " + newKeywordString);
        // make sure stored keywords are loaded
        Collection<String> keywords = getStoredKeywords();

        if (!keywords.contains(newKeywordString)) {
            DirContext dirContext = getDirectoryContext();
            try {
                Attributes attrs = new BasicAttributes("keywords", newKeywordString);
                dirContext.modifyAttributes("cn=jimConfig", DirContext.ADD_ATTRIBUTE, attrs);
            } catch (NamingException e) {
                LOG.error("Naming exception adding Keyword", e);
            } finally {
                cleanup(dirContext);
            }
            keywords.add(newKeywordString);
            LOG.debug("Keyword added " + newKeywordString);
        } else {
            LOG.debug("Keyword already exists " + newKeywordString + " in " + keywords);
        }
    }

    /**
     * @param oldKeyword
     * @param newKeyword
     *            null = remove the keyword
     */
    public void updateKeyword(String oldKeyword, String newKeyword) {

        LOG.debug("Updating keyword " + oldKeyword + " with " + newKeyword);
        DirContext dirContext = getDirectoryContext();
        try {

            // Search could possibly be slightly more efficient match the check
            // below (equals or startswith old+"~")
            String keywordSearch = "(keywords=" + oldKeyword + "*)";

            NamingEnumeration<SearchResult> names = dirContext.search("", keywordSearch, new SearchControls(
                    SearchControls.ONELEVEL_SCOPE, 0, 0, new String[]{"keywords"}, false, false));

            BasicAttribute newAttribute = new BasicAttribute("keywords");
            BasicAttribute oldAttribute = new BasicAttribute("keywords");

            while (names.hasMoreElements()) {

                SearchResult searchResult = names.nextElement();
                Attribute keywordAttribute = searchResult.getAttributes().get("keywords");

                // Prepare the modification items.
                oldAttribute.clear();
                newAttribute.clear();

                for (int i = 0; i < keywordAttribute.size(); i++) {
                    String oldKeywordString = (String) keywordAttribute.get(i);
                    if (AbstractImageBase.isKeywordRelated(oldKeywordString, oldKeyword)) {

                        // Create mod item to remove the old keyword
                        oldAttribute.add(oldKeywordString);

                        if (newKeyword != null) {
                            // Create mod item to add the new keyword
                            String newKeywordString = newKeyword + oldKeywordString.substring(oldKeyword.length());
                            // String newKeywordString =
                            // oldKeywordString.replaceFirst(oldKeyword,
                            // newKeyword);
                            newAttribute.add(newKeywordString);
                        }
                    }

                }

                int modItemCount = Integer.signum(oldAttribute.size()) + (newKeyword == null ? 0 : 1);
                if (modItemCount > 0) {
                    ModificationItem[] mods = new ModificationItem[modItemCount];
                    int modItem = 0;

                    // If remove attribute has no values ALL values are removed.
                    if (oldAttribute.size() > 0) {
                        mods[modItem++] = new ModificationItem(DirContext.REMOVE_ATTRIBUTE, oldAttribute);
                    }

                    if (newAttribute.size() > 0) {
                        mods[modItem++] = new ModificationItem(DirContext.ADD_ATTRIBUTE, newAttribute);
                    }

                    dirContext.modifyAttributes(searchResult.getName(), mods);
                }
            }

        } catch (NamingException ne) {
            LOG.error("Naming exception replacing " + oldKeyword + "with " + newKeyword, ne);
        } finally {
            cleanup(dirContext);
        }

        getStoredKeywords().remove(oldKeyword);
        if (newKeyword != null) {
            getStoredKeywords().add(newKeyword);
        }
    }

    /**
     * @param oldKeyword
     */
    public void removeKeyword(String oldKeyword) {

        updateKeyword(oldKeyword, null);

    }

    public Set<ImageBaseDirectory> findOnPath(File dirFile) {

        dirFile = ImageBaseDirectory.convertToImageBaseFile(dirFile);
        return search("path=" + dirFile.toString().replaceAll("\\\\", "\\\\\\\\"));

    }

    public QueryCondition getEqualsCondition(String attributeName, String literalValue) {

        return new LDAPEqualsCondition(attributeName, literalValue);
    }

    public Collection<ImageBaseDirectory> search(QueryCondition condition) {

        LDAPCondition ldapCondition = (LDAPCondition) condition;
        return search(ldapCondition.getQueryString());

    }

    public CombinationCondition getCombinationCondition(boolean andMatch) {

        return new LDAPCombinationCondition(andMatch);
    }

}